import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //全局变量
    car: [
    ],
  },
  mutations: {  //修改状态，是同步的
    add(state, shopcar) {   //第一个·参数不可以改变，必须传state,第二个参数传过来的数据
      var flag = false;
      state.car.some(item => {
        if (item.id == shopcar.id) {
          item.num += parseInt(shopcar.num);
          flag = true;
          return true;
        }
      })
      if (!flag) {
        state.car.push(shopcar);
        var user = localStorage.getItem("user")
        localStorage.setItem(user, JSON.stringify(state.car))
      }
    },
    jian(state, index) {
      state.car[index].num++
      var user = localStorage.getItem("user")
      localStorage.setItem(user, JSON.stringify(state.car))
    },
    jia(state, index) {
      if (state.car[index].num > 0) {
        state.car[index].num--
        var user = localStorage.getItem("user")
        localStorage.setItem(user, JSON.stringify(state.car))
      }

    },
    blur(state, arr) {
      state.car[arr[0]].num = parseInt(arr[1]);
      var user = localStorage.getItem("user")
      localStorage.setItem(user, JSON.stringify(state.car))
    },
    remove(state, index) {
      state.car.splice(index, 1);
      var user = localStorage.getItem("user")
      localStorage.setItem(user, JSON.stringify(state.car))
    },
    removeAll(state) {
      var user = localStorage.getItem("user") // 本地存储
      localStorage.setItem(user + "finish", JSON.stringify(state.car))
      localStorage.removeItem(user)
    },

  },
  actions: {
  },
  modules: {
  }
})
